const Promise = require('bluebird');

/**
 * 浏览记录
 */
exports.browseViews = function ({query, user}, {modelsData: {Goodses}, models: {UsersViews}, controller}) {
    query.user_id = user.id;
    query.limit = 20;

    return UsersViews.findAll(controller.pagination({
        params: query,
        filters: ['user_id'],
        order: [['id', 'desc']]
    })).then(function (rows) {
        let ids = [];
        for (let i in  rows) {
            let row = rows[i];
            ids.push(row.goods_id);
        }
        return Goodses.browseV2({goods_ids: ids}).then(function (items) {
            let map = {};
            for (let i in items) {
                let item = items[i];
                map[item.auctionId] = item;
            }

            let newRows = [];
            for (let i in ids) {
                let id = ids[i];
                if (map[id]) {
                    newRows.push(map[id]);
                }
            }

            return {query: query, rows: newRows, classNames: 'browse-item'};
        });
    });
}

/**
 * 搜索记录
 */
exports.browseSearch = function ({query, user}, {modelsData: {Goodses}, models: {UsersSearchs}, controller}) {
    query.user_id = user.id;
    query.goods_id = {$ne: ''};
    query.limit = 20;

    return UsersSearchs.findAll(controller.pagination({
        params: query,
        filters: ['user_id', 'goods_id'],
        order: [['id', 'desc']]
    })).then(function (rows) {
        let ids = [];
        for (let i in  rows) {
            let row = rows[i];
            ids.push(row.goods_id);
        }
        return Goodses.browseV2({goods_ids: ids}).then(function (items) {
            let map = {};
            for (let i in items) {
                let item = items[i];
                map[item.auctionId] = item;
            }

            let newRows = [];
            for (let i in ids) {
                let id = ids[i];
                if (map[id]) {
                    newRows.push(map[id]);
                }
            }

            return {query: query, rows: newRows, classNames: 'browse-item'};
        });
    });
}

/**
 * 同店商品
 */
exports.storeGoodses = function ({query, user}, {modelsData: {Goodses}, controller}) {
    let {auctionId, sellerId} = query;
    return Goodses.browseV2({
        sellerId: sellerId,
        auctionId: auctionId,
        limit: 10
    }).then(function (rows) {
        return {query: query, rows: rows, classNames: 'browse-item'};
    });
}

/**
 * 搜索
 */
exports.search = function ({query, user}, {modelsData: {Goodses}, models: {}, cache: {settings}, search: {searchEnable, goodsesSearch}, spider}) {
    if (searchEnable) {
        return goodsesSearch.search(query).then(function (result) {
            let {rows, count} = result, ids = [];
            for (let i in rows) {
                let row = rows[i];
                ids.push(row.id);
            }
            if (!ids.length) {
                return {count: count, rows: [], classNames: 'search-item'};
            }

            return Goodses.browseV2({ids: ids}).then(function (goodses) {
                let map = {};
                for (let i in goodses) {
                    let goods = goodses[i];
                    map[goods.id] = goods;
                }
                let items = [];
                for (let i in ids) {
                    let id = ids[i];
                    if (map[id]) {
                        items.push(map[id]);
                    }
                }
                return {query: query, count: count, rows: items, classNames: 'search-item'};
            });
        }).then(function (result) {
            if (query.keyword && query.keyword.length > 10 && query.limit && query.limit > result.rows.length) {
                return spider.alimamaSearch({title: query.keyword, pageSize: 20}).then(function (res) {
                    if (res.success) {
                        if (res.data && res.data.length) {
                            result.rows = result.rows.concat(res.data);
                        }
                    }
                    return result;
                });
            }
            return result;
        });
    }
    return {count: 0, rows: []};
}

/**
 * 浏览
 */
exports.browse = function ({body, user}, {modelsData: {Categories, Goodses}, models: {UsersSearchs}, spider, utils}) {
    let {catIds, sort, keyword, offset} = body;
    let handleByTitle = function () {
        let arr = (keyword || '').match(/（(.*?)）/i);
        if (arr && arr[1]) {
            keyword = arr[1];
        }

        if (!parseInt(offset)) {
            if (keyword && user) {
                UsersSearchs.destroy({where: {keyword: keyword, user_id: user.id, goods_id: ''}}).then(function () {
                    return UsersSearchs.create({
                        keyword: keyword,
                        user_id: user.id,
                        goods_id: '',
                        agency_id: user.agency_id
                    });
                }).catch(function (err) {
                    console.error('保存用户搜索记录异常', {
                        keyword: keyword,
                        user_id: user.id,
                        goods_id: '',
                        agency_id: user.agency_id
                    });
                });
            }
        }

        return Promise.resolve().then(function () {
            if (!catIds || catIds == 'all') {
                return false;
            }
            return Categories.findOne({where: {id: catIds}, attributes: ['leafCatIds']});
        }).then(function (cat) {
            if (cat) {
                body.leafCatId = JSON.parse(cat.leafCatIds);
            }
            let order = 'g.feature desc, g.order_by desc, g.id asc';
            if (sort == 'new') {
                order = 'g.created_at desc, g.feature desc, g.order_by desc, g.id asc';
            } else if (sort == 'sales') {
                order = 'g.biz30day desc, g.feature desc, g.order_by desc, g.id asc';
            } else if (sort == 'sales') {
                order = 'g.biz30day desc, g.feature desc, g.order_by desc, g.id asc';
            } else if (sort == 'quan') {
                order = 'g.couponAmount desc, g.feature desc, g.order_by desc, g.id asc';
            } else if (sort == 'price_asc') {
                order = 'g.quanPrice asc, g.feature desc, g.order_by desc, g.id asc';
            } else if (sort == 'price_desc') {
                order = 'g.quanPrice desc, g.feature desc, g.order_by desc, g.id asc';
            }
            return Goodses.browseV2(body, order).then(function (rows) {
                return {query: body, rows: rows, classNames: 'browse-item'};
            });
        });
    }

    if (keyword) {
        let handle = function (url) {
            return utils.getRealUrl(url).then(function (realUrl) {
                let id = utils.getQueryString(realUrl, 'id');

                if (user) {
                    UsersSearchs.destroy({where: {keyword: '', goods_id: id, user_id: user.id}}).then(function () {
                        return UsersSearchs.create({
                            keyword: '',
                            goods_id: id,
                            user_id: user.id,
                            agency_id: user.agency_id
                        });
                    }).catch(function (err) {
                        console.error('保存用户搜索记录异常', {
                            keyword: '',
                            goods_id: id,
                            user_id: user.id,
                            agency_id: user.agency_id
                        });
                    });
                }

                return {id: id};
            });
        }

        let arr = keyword.match(/(http.*?)(，|\s|$)/i);
        if (arr && arr[1]) {
            let url = arr[1];
            return handle(url);
        }

        arr = keyword.match(/￥(.*?)￥/i);
        if (arr && arr[0]) {
            let kouling = arr[0];
            return spider.restoreTaokouling(kouling).then(function (result) {
                if (result && result.url) {
                    return handle(result.url);
                }
                return handleByTitle();
            });
        }
    }
    return handleByTitle();
}

/**
 * 领取优惠券
 */
exports.popcoupon = function ({query, user, req}, {models: {Users}, cache: {settings}, spider, redis, config}) {
    let {activityId, itemId, quan_amount, isWechat} = query;
    let getAgency = function () {
        return Promise.resolve().then(function () {
            if (user) {
                if (user.level === 'Agency' || user.level === 'Partner') {
                    return user;
                }
                return Users.findOne({where: {id: user && user.agency_id || 1}});
            }
            let domain = req.hostname;
            let inviter_id = req.session.inviter_id;

            // console.log('domain', domain);
            return Users.findOne({where: {$or: {domain: domain, id: inviter_id}}}).then(function (agency) {
                if (agency) {
                    if (agency.domain_pid) {
                        agency.pid = agency.domain_pid;
                    }
                    return agency;
                }
                return Users.findOne({where: {id: 1}});
            });
        });
    }
    return getAgency().then(function (agency) {
        let cacheKey = 'popcoupon_' + itemId + '_' + activityId + '_' + agency.id;
        return redis.cache(cacheKey, 60 * 60, function () {
            return Promise.props({
                goods: spider.getGoodsByAuctionId({id: itemId, user_id: user && user.id}),
                coupon: activityId ? {activity_id: activityId, quan_amount: (parseFloat(quan_amount) || 0)} : null
            }).then(function ({goods, coupon}) {
                return spider.getBuyKouling({
                    goods: goods,
                    coupon: coupon,
                    user: user,
                    agency: agency
                }).then(function (text) {
                    let iosText = '';
                    if (text) {
                        iosText = text.replace(/\r\n/g, "<BR>");
                        iosText = text.replace(/\n/g, "<BR>");
                    }
                    return {
                        goods: goods,
                        coupon: coupon,
                        text: text,
                        iosText: iosText
                    }
                });
            });
        }).then(function (result) {
            let text = result.text;
            if (text && text.indexOf('￥') == -1 && text.indexOf('《') == -1 && text.indexOf('€') == -1) {
                redis.globalClient.del(cacheKey);
            }
            return result;
        });
    });
}

/**
 * 店铺优惠券
 * 判断是否优惠券可用
 */
exports.storeCoupons = function ({query, user_id}, {models: {Users}, cache: {settings}, spider}) {
    let {pid, auctionId, zkPrice, seller_id, isWechat} = query;
    if (!seller_id) {
        return {success: false, message: '参数错误'};
    }
    return {
        user_id: user_id,
        pid: pid,
        auctionId: auctionId,
        zkPrice: zkPrice,
        coupons: [],
        browsersBuy: (isWechat == 0) ? true : false
    };
}

/**
 * 商品优惠券
 * 判断是否优惠券可用，设置最高优惠券到商品
 */
exports.goodsCoupons = function ({query, user, user_id}, {models: {Users}, cache: {settings}, spider}) {
    let {pid, auctionId, tkMktStatus, zkPrice, seller_id, isWechat} = query;
    if (!auctionId || !seller_id) {
        return {success: false, message: '参数错误'};
    }
    return {
        user_id: user_id,
        pid: pid,
        auctionId: auctionId,
        zkPrice: zkPrice,
        coupons: [],
        isMt: parseInt(tkMktStatus) || 0,
        isGoods: true,
        browsersBuy: (isWechat == 0) ? true : false
    };
}

/**
 * 价格走势
 */
exports.priceTrend = function ({query, user_id}, {models: {Users}, cache: {settings}, utils, redis, spider}) {
    let {url} = query;
    let id = utils.getQueryString(url, 'id');
    return redis.cache('price_trend_' + id, 60 * 60, function () {
        return spider.priceTrend({url: url}).then(function (result) {
            if (!result.success) {
                return result;
            }
            result = result.data;

            let list = result.priceHistoryData.list;
            let labels = [], data = [];
            for (let i in list) {
                let price = list[i];
                labels.push('"' + price.time + '"');
                data.push(price.price);
            }
            result.chart = {
                labels: labels.join(','),
                data: data.join(',')
            }
            return result;
        });
    });
}

/**
 * 阿里妈妈搜索
 */
exports.alimamaSearch = function ({body, user_id}, {models: {Users}, cache: {settings}, utils, redis, spider}) {
    return spider.alimamaSearch(body).then(function (result) {
        if (result.success) {
            return {rows: result.data || []};
        } else {
            return {rows: []};
        }
    });
}